/***************************************************************************************
* Copyright (c) 2014-2022 Zihao Yu, Nanjing University
*
* NEMU is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*          http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*
* See the Mulan PSL v2 for more details.
***************************************************************************************/

#include <isa.h>
#include <memory/paddr.h>
#include <elf.h>
#include <sys/mman.h> /* mmap() */
#include <stdint.h>
#include <sys/stat.h> /* fstat() */
#include <fcntl.h>
void init_rand();
void init_log(const char *log_file);
void init_mem();
void init_difftest(char *ref_so_file, long img_size, int port);
void init_device();
void init_sdb();
void init_disasm(const char *triple);
#ifdef CONFIG_FTRACE
/// /////////////////////////////
//// elf文件解析部分
//////////////////////////////////
// #include <stdio.h>
// #include <string.h>
// #include <error.h>

// #include <unistd.h>
// #include <stdlib.h>

typedef struct func {
  word_t start;
  word_t size;
  word_t end;
  struct func *next;
  char  name [100];
} FC;
static FC *func_w = NULL;
 FC *fc_head=NULL;
static FC fc_pool [240] = {};
// static 
char func_ [9][32];
void init_fc_pool() {
    int i;
    for (i = 0; i < 240; i ++) {
        fc_pool[i].start = 0;
        fc_pool[i].size = 0;
        fc_pool[i].end = 0;
        fc_pool[i].next = (i == 240 - 1 ? NULL : &fc_pool[i + 1]);
    }
    func_w = fc_pool;
    fc_head = NULL;
}
void write_wp(word_t start,word_t size,word_t end,char * func_name){
    FC *p=NULL;
    FC *n=NULL;
    p = fc_head;
    n = func_w;
    func_w = func_w->next;
    n->start = start;
    n->size = size;
    n->end = end;
    n->next = NULL;
    memcpy(n->name,func_name,strlen(func_name)+1);    
    // printf("%d,%d,%d,%s\n",n->start,n->size,n->end,n->name);
    if(p ==NULL){
        fc_head = n;
        p = fc_head;
    }
    else{
        while (p->next)
        {
        p = p->next;
        }
        p->next = n;
    }
};

void add_elf(char * file){
    //  = "test.o";
    int fd;
    uint8_t *mem;
    uint64_t sym_num = 0;
    struct stat st;
    Elf64_Ehdr *ehdr; /* ELF头 */
    Elf64_Shdr *shdr; /* 节头 */
    Elf64_Sym  *sym = NULL;  /* 符号 */
    unsigned char *sht_symtab= NULL, *temp1= NULL,*temp2 = NULL;///*sht_strtab,
    uint16_t  section_num;
    size_t  symtab_num=0;//,shstr_num,str_num;
    init_fc_pool();
    fd = open(file,O_RDONLY);
    if (fstat(fd, &st) < 0) {
        perror("fstat");
        assert(0);
    }
    /* 映射可执行文件 */
    mem = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
    if (mem == NULL) {
        perror("mmap");
        assert(0);
    }
    /* ELF文件头起始于文件的0偏移 */
    ehdr = (Elf64_Ehdr *) mem;

    shdr = (Elf64_Shdr *) &mem[ehdr->e_shoff];
    section_num = ehdr->e_shnum;
    for (size_t i = 0; i < section_num; i++)
    {
        if (shdr[i].sh_type==SHT_SYMTAB)
        {
            sht_symtab = &mem[shdr[i].sh_offset];
            sym_num    = shdr[i].sh_size / shdr[i].sh_entsize;
            sym = (Elf64_Sym *) sht_symtab;
            symtab_num = i;
        }
    }
    for (size_t i = 0; i < section_num; i++)
    {
        if (shdr[i].sh_type==SHT_STRTAB )
        {
            temp1 =  &mem[shdr[i].sh_offset];
            // shstr = (Elf64_Sym *) temp1;
            if(!strcmp((char *)&temp1[shdr[symtab_num].sh_name], ".symtab")){
                // shstr_num = i;
                // shstr = (Elf64_Sym *) temp1;
                break;
            }
        }
    } 
    for (size_t i = 0; i < section_num; i++)
    {
        if(!strcmp((char *)&temp1[shdr[i].sh_name], ".strtab")){
            // str_num = i;
            temp2 =  &mem[shdr[i].sh_offset];
            // str = (Elf64_Sym *) &mem[shdr[i].sh_offset];
        }
    } 
    char fun_name[64];
    for (size_t i = 0; i < sym_num; i++)
    {
        if (sym[i].st_info%4 == STT_FUNC && sym[i].st_size)
        {
            sprintf(fun_name,"%s",&temp2[sym[i].st_name]);
            write_wp(sym[i].st_value,sym[i].st_size,sym[i].st_value+sym[i].st_size-4,fun_name);
        }
    }
    FC *p=fc_head;
    while (p)
    {
      printf("0x%lx,0x%lx,0x%lx,%s\n",p->start,p->size,p->end,p->name);
      p=p->next;
    }
}
#endif
////////////////////////////////
////////////////////////////////

static void welcome() {
  Log("Trace: %s", MUXDEF(CONFIG_TRACE, ANSI_FMT("ON", ANSI_FG_GREEN), ANSI_FMT("OFF", ANSI_FG_RED)));
  IFDEF(CONFIG_TRACE, Log("If trace is enabled, a log file will be generated "
        "to record the trace. This may lead to a large log file. "
        "If it is not necessary, you can disable it in menuconfig"));
  Log("Build time: %s, %s", __TIME__, __DATE__);
  printf("Welcome to %s-NEMU!\n", ANSI_FMT(str(__GUEST_ISA__), ANSI_FG_YELLOW ANSI_BG_RED));
  printf("For help, type \"help\"\n");
  //Log("Exercise: Please remove me in the source code and compile NEMU again.");
  //assert(0);
}

#ifndef CONFIG_TARGET_AM
#include <getopt.h>

void sdb_set_batch_mode();

static char *log_file = NULL;
static char *diff_so_file = NULL;
static char *img_file = NULL;
static int difftest_port = 1234;

static long load_img() {
  if (img_file == NULL) {
    Log("No image is given. Use the default build-in image.");
    return 4096; // built-in image size
  }

  FILE *fp = fopen(img_file, "rb");
  Assert(fp, "Can not open '%s'", img_file);

  fseek(fp, 0, SEEK_END);//设置流 stream 的文件位置为给定的偏移 offset，参数 offset 意味着从给定的 whence（从何处; 从哪里;） 位置查找的字节数。
  long size = ftell(fp);//ftell用于获取文件位置指针当前位置相对于文件首的偏移字节数。

  Log("The image is %s, size = %ld", img_file, size);

  fseek(fp, 0, SEEK_SET);
  int ret = fread(guest_to_host(RESET_VECTOR), size, 1, fp);
  assert(ret == 1);

  fclose(fp);
  return size;
}

static int parse_args(int argc, char *argv[]) {
  const struct option table[] = {
    {"batch"    , no_argument      , NULL, 'b'},
    {"log"      , required_argument, NULL, 'l'},
    {"diff"     , required_argument, NULL, 'd'},
    {"port"     , required_argument, NULL, 'p'},
    {"help"     , no_argument      , NULL, 'h'},
  #ifdef CONFIG_FTRACE
    {"elf"      , required_argument, NULL, 'e'},
  #endif
    {0          , 0                , NULL,  0 },
  };
  int o;
  while ( (o = getopt_long(argc, argv, "-bhl:d:p:", table, NULL)) != -1) {
    switch (o) {
      case 'b': sdb_set_batch_mode(); break;
      case 'p': sscanf(optarg, "%d", &difftest_port); break;
      case 'l': log_file = optarg; break;
      case 'd': diff_so_file = optarg; break;
#ifdef CONFIG_FTRACE
      case 'e': add_elf(optarg); break;
#endif
      case 1: img_file = optarg; return 0;
      default:
        printf("Usage: %s [OPTION...] IMAGE [args]\n\n", argv[0]);
        printf("\t-b,--batch              run with batch mode\n");
        printf("\t-l,--log=FILE           output log to FILE\n");
        printf("\t-d,--diff=REF_SO        run DiffTest with reference REF_SO\n");
        printf("\t-p,--port=PORT          run DiffTest with port PORT\n");
        printf("\n");
        exit(0);
    }
  }
  return 0;
}

void init_monitor(int argc, char *argv[]) {
  /* Perform some global initialization. */

  /* Parse arguments. */
  parse_args(argc, argv);

  /* Set random seed. */
  init_rand();

  /* Open the log file. */
  init_log(log_file);

  /* Initialize memory. */
  init_mem();

  /* Initialize devices. */
  IFDEF(CONFIG_DEVICE, init_device());

  /* Perform ISA dependent initialization. */
  init_isa();

  /* Load the image to memory. This will overwrite the built-in image. */
  long img_size = load_img();

  /* Initialize differential testing. */
  init_difftest(diff_so_file, img_size, difftest_port);

  /* Initialize the simple debugger. */
  init_sdb();

  IFDEF(CONFIG_ITRACE, init_disasm(
    MUXDEF(CONFIG_ISA_x86,     "i686",
    MUXDEF(CONFIG_ISA_mips32,  "mipsel",
    MUXDEF(CONFIG_ISA_riscv32, "riscv32",
    MUXDEF(CONFIG_ISA_riscv64, "riscv64", "bad")))) "-pc-linux-gnu"
  ));

  /* Display welcome message. */
  welcome();
}
#else // CONFIG_TARGET_AM
static long load_img() {
  extern char bin_start, bin_end;
  size_t size = &bin_end - &bin_start;
  Log("img size = %ld", size);
  memcpy(guest_to_host(RESET_VECTOR), &bin_start, size);
  return size;
}

void am_init_monitor() {
  init_rand();
  init_mem();
  init_isa();
  load_img();
  IFDEF(CONFIG_DEVICE, init_device());
  welcome();
}
#endif
